import Vue from 'vue'
import iView from 'iview'
import { router } from './router/index'
import store from './store'
import App from './app.vue'
import Viewer from 'v-viewer'

import 'viewerjs/dist/viewer.css'
import 'iview/dist/styles/iview.css'
import './styles/theme.less'
import './styles/common.less'
import VueAMap from 'vue-amap'
import './libs/dateFormat'
import filters from './filters'
import components from './components'
import directives from './directives'
// 全局filter
Object.keys(filters).forEach(key => Vue.filter(key, filters[key]))
Object.keys(directives).forEach(key => Vue.directive(key, directives[key]))
Vue.use(Viewer)
/**
 * 监听登录接口刷新
 * IE有问题..当前页面也会刷新
 */
window.onstorage = function (e) {
  if (e.key === 'last_login_req_id' && e.newValue !== window.last_login_req_id) {
    location.reload()
  }
}

Vue.use(components)
/**
 * 生成螺丝帽图形验证码
 * 每次添加script标签请求js
 */
Vue.prototype.createLuosimao = function () {
  let lastScript = document.getElementsByClassName('luo-si-mao')[0]
  if (lastScript) {
    lastScript.parentNode.removeChild(lastScript)
  }

  let c = document.createElement('script')
  c.type = 'text/javascript'
  c.className = 'luo-si-mao'
  c.async = true
  c.src = '//captcha.luosimao.com/static/dist/captcha.js?v=201707071250'

  // js请求完毕后重置验证码
  c.onload = function () {
    window.LUOCAPTCHA && window.LUOCAPTCHA.reset()
  }
  let s = document.getElementsByTagName('script')[0]
  s.parentNode.insertBefore(c, s)
}

Vue.use(iView)
Vue.use(VueAMap)

// 初始化vue-amap
VueAMap.initAMapApiLoader({
  // 高德的key
  key: '45717c9ccc0a2e5009cdd7b391fbdbd3',
  // 插件集合
  plugin: [
    'AMap.Autocomplete',
    'AMap.PlaceSearch',
    'AMap.Scale',
    'AMap.OverView',
    'AMap.ToolBar',
    'AMap.MapType',
    'AMap.PolyEditor',
    'AMap.CircleEditor'
  ],
  // 高德 sdk 版本，默认为 1.4.4
  v: '1.4.4'
})

// 权限指令
Vue.directive('pmis', {
  inserted (el, binding) {
    // const allPermission = localStorage.permission ? JSON.parse(localStorage.permission) : [];
    // const parentNode = el.parentNode;
    // const nextElementSibling = el.nextElementSibling;
    // const permission = binding.value;

    // parentNode.removeChild(el); // 移除DOM
    // let hasPermission = false;

    // if (typeof permission === 'number' && allPermission[permission]) {
    //     hasPermission = true; // 单个权限
    // } else if (typeof permission === 'object') {
    //     hasPermission = true; // 多个权限
    //     for (let key in permission) {
    //         if (!allPermission[permission[key]]) {
    //             hasPermission = false;
    //             return;
    //         }
    //     }
    // }

    // if (hasPermission) {
    //     parentNode.insertBefore(el, nextElementSibling);
    // }
  }
})

new Vue({
  el: '#app',
  router: router,
  store: store,
  render: h => h(App),
  data: {
    currentPageName: ''
  },
  mounted () {
    this.currentPageName = this.$route.name
    this.$Message.config({
      top: 50,
      duration: 2
    })
  }
})
